package com.okcl.easychat.handler;

import com.okcl.easychat.bean.SessionBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * web socket 主处理程序
 */
@Slf4j
@Component
public class WsHandler extends AbstractWebSocketHandler {

    private static final Map<String, SessionBean> sessionBeanMap;
    private static final AtomicInteger clientIdMaker;//考虑线程安全
    private static final StringBuffer stringBuffer;//存储信息

    //初始化
    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        clientIdMaker = new AtomicInteger(0);
        stringBuffer = new StringBuffer();
    }

    /**
     * 群发
     *
     * @param sessionBeanMap
     * @throws IOException
     */
    private static void sendAll(Map<String, SessionBean> sessionBeanMap) throws IOException {
        for (String key : sessionBeanMap.keySet()) {
            sessionBeanMap.get(key).getWebSocketSession().sendMessage(new TextMessage(stringBuffer.toString()));
        }
    }

    /**
     * 连接建立成功后
     *
     * @param session
     * @throws Exception
     */

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        SessionBean sessionBean = new SessionBean(session, clientIdMaker.getAndIncrement());//返回当前的值并且自增
        sessionBeanMap.put(session.getId(), sessionBean);
        log.info("{}连接成功...", sessionBean.getClientId());
        super.afterConnectionEstablished(session);
        stringBuffer.append(sessionBean.getClientId() + ":" + "连接成功" + "\n");
        //进行群发
        sendAll(sessionBeanMap);
    }

    /**
     * 收到消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到 {} 消息：{}", sessionBeanMap.get(session.getId()).getClientId(), message.getPayload());
        super.handleTextMessage(session, message);
        stringBuffer.append(sessionBeanMap.get(session.getId()).getClientId() + ":" + message.getPayload() + "\n");
        sendAll(sessionBeanMap);
    }

    //传输异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        //如果该session是打开的，则关闭它
        if (session.isOpen()) {
            session.close();
        }
        sessionBeanMap.remove(session.getId());
    }

    //连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        log.info("{}连接关闭...", sessionBeanMap.get(session.getId()).getClientId());
        stringBuffer.append(sessionBeanMap.get(session.getId()).getClientId() + ":" + "连接关闭" + "\n");
        sessionBeanMap.remove(session.getId()); // 从 map 中移除已关闭的会话
        sendAll(sessionBeanMap);
    }

//    //每两秒钟给所有用户发消息
//    @Scheduled(fixedRate = 2000)//2000毫秒
//    public void sendMsg() throws IOException {
//        for (String key : sessionBeanMap.keySet()) {
//            sessionBeanMap.get(key).getWebSocketSession().sendMessage(new TextMessage("hello"));
//        }
//    }
}
